package Model.InboxMessages;

import DBAccess.DBAccess;
import java.sql.Date;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mysql.jdbc.PreparedStatement;

public class Inbox {
  
  public void createMessage(Message message) {
	  
  }

  public static ArrayList<SimpleMessage> getMessages(int userID, int start){
	  new DBAccess();
	  ArrayList<SimpleMessage> messageList = new ArrayList<SimpleMessage>();
	  Statement ps = null;
	  ResultSet rs = null;
	  int numOfMsgs = 8;
	  System.out.println("starting at"+start);
	  String query = "SELECT * from inboxdb where toID="+userID +" OR fromID="+userID+" LIMIT "+start+", "+numOfMsgs;
	  try {
		ps = DBAccess.con.createStatement();
		rs = ps.executeQuery(query);
		while(rs.next()){
			int messageID = rs.getInt("messageID");
			int fromID = rs.getInt("fromID");
			int toID = rs.getInt("toID");
			int fromDeleteFlag = rs.getInt("fromDeleteFlag");
			int toDeleteFlag = rs.getInt("toDeleteFlag");
			String message = rs.getString("message");
			Date time = rs.getDate("messageTime");
			if((fromID==userID && fromDeleteFlag == 1)||(toID==userID && toDeleteFlag==1)){
				continue;
			}
			Message msg = new Message(messageID, fromID, toID,message, time);
			messageList.add(msg.inboxDisplay());
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	  DBAccess.close(ps,rs);

	  return messageList;
	  
  }

  public static Message viewMessage(int messageID) {
	  new DBAccess();
	  Statement ps = null;
	  ResultSet rs = null;
	  Message msg = null;
	  String query = "SELECT * from inboxdb where messageID="+messageID;
	  try {
		ps = DBAccess.con.createStatement();
		rs = ps.executeQuery(query);
		while(rs.next()){
			int msgID = rs.getInt("messageID");
			int fromID = rs.getInt("fromID");
			int toID = rs.getInt("toID");
			int fromDeleteFlag = rs.getInt("fromDeleteFlag");
			int toDeleteFlag = rs.getInt("toDeleteFlag");
			String message = rs.getString("message");
			Date time = rs.getDate("messageTime");
			msg = new Message(msgID, fromID, toID,message, time);
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	  DBAccess.close(ps,rs);

	  return msg;
  }

  public static void deleteMessage(int messageID) {
	  new DBAccess();
	  java.sql.PreparedStatement  ps = null;
	  ResultSet rs = null;
	  Message msg = null;
	  String query = "DELETE from inboxdb where messageID="+messageID;
	  try {
		ps = DBAccess.con.prepareStatement(query);
		ps.executeUpdate();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	  DBAccess.close(ps,rs);
  }

}